import { reactive } from "vue";
import { request } from "./axios";
import { ElMessageBox } from "element-plus";
import iconRobot1 from './assets/robot.png'
import iconRobot2 from './assets/robot_red.png'

const genKey = ((k = 1) => () => k++)()

export const state = reactive({
  msgList: [],
  currentRobot: 'test1',
  robots: [
    { value: 'test1', icon: iconRobot1 },
    { value: 'test2', icon: iconRobot2 },
  ]
})

const clear = () => {
  state.msgList = []
}

export const switchRobot = async robot => {
  if (state.msgList.length) {
    await ElMessageBox.confirm('这将清空当前会话历史，确定切换机器人？', '切换机器人', {
      confirmButtonText: '确定',
      cancelButtonText: '取消'
    })
  }
  state.currentRobot = robot
  clear()
}

export const startNew = async () => {
  if (state.msgList.length) {
    await ElMessageBox.confirm('这将清空当前会话历史，确定开始新会话？', '开始新会话', {
      confirmButtonText: '确定',
      cancelButtonText: '取消'
    })
  }
  clear()
}

export const addMessage = msg => state.msgList.push(msg)

export const updateMessage = (id, attrs) => {
  const index = state.msgList.findIndex(_ => _.id === id)
  state.msgList.splice(index, 1, { ...state.msgList[index], ...attrs })
}

const getHistory = () => {
  const len = state.msgList.length
  for (let i = len - 1; i >= 0; i--) {
    const item = state.msgList[i]
    if (item.history) {
      return item.history
    }
  }
  return []
}

const sendLocalDocChat = msg => {
  return request.post('/local_doc_qa/local_doc_chat', {
    ...msg,
    knowledge_base_id: state.currentRobot
  })
}

export const sendMsg = async question => {
  const id = genKey()
  addMessage({
    id,
    isSelf: true,
    loading: true,
    error: false,
    content: question
  })
  try {
    const result = await sendLocalDocChat({
      question,
      history: getHistory()
    })
    addMessage({
      ...result,
      id: genKey(),
      content: result.response.replace(/\n/gm, '<br>'),
      icon: (state.robots.find(_ => _.value === state.currentRobot) || {}).icon
    })
    updateMessage(id, { loading: false })
  } catch (e) {
    updateMessage(id, { error: true, loading: false })
  }
}
